#include <string.h>
#include "uart.h"
/*
typedef struct _ST_CirQueue
{
    C_U8*           m_pu8Data;
    C_U16           m_u16Size;//缓存区大小
    C_U16           m_u16Front;
    C_U16           m_u16Rear;
    C_U16           m_u16Count;//缓存区中的数据大小
} ST_CirQueue;
*/
uint8_t uartData[1024] = 0;
ST_CirQueue  m_stRecvQueue;


int main(void) 
{
	CirQueue_Init(&m_stRecvQueue, uartData, sizeof(uartData));
	uint8_t  m_arru8RecvVariant[32 * 2];
    uint8_t  m_arru8RecvRestore[32];

    while(1)
	{
		if((uart1_rx_handle()))
		{
			CirQueue_EnBlock(&m_stRecvQueue, uart1_data.data, uart1_data.index);
			uart1_data.index = 0;
			memset(uart1_data.data, 0, sizeof(uart1_data.data));
		}
				
		if(!CirQueue_isEmpty(a_pstCirQueue))
		{
			uint8_t u8VBuffSize = sizeof(m_arru8RecvVariant);
			if(GetPack(&m_stRecvQueue,m_arru8RecvVariant,&u8VBuffSize))
			{
				uint8_t u8RBuffSize = 0;
				if(VariantToRestore(m_arru8RecvVariant,u8VBuffSize,m_arru8RecvRestore,&u8RBuffSize))                         
				{										
					SerialTransRecvCb(m_arru8RecvRestore+2, u8RBuffSize-4);	
					...
				}
			}
		}
    }
}

static C_BOOL GetPack(ST_CirQueue* a_pstCirQueue, C_U8* a_pu8Buff, C_U8* a_pu8BuffSize)
{
    C_ACHAR strHead[3] = {0xaa, 0xaa, '\0'};
    C_ACHAR strTail[3] = {0x55, 0x55, '\0'};

    if (CirQueue_isEmpty(a_pstCirQueue))
        return C_FALSE;

    #if 0
    CirQueue_Print(a_pstCirQueue, 1); // echo
    #endif

    C_S16 s16HeadPos = CirQueue_FindStr(a_pstCirQueue, strHead);
    if (-1 == s16HeadPos) // no head, clean all the data
    {
        #if 0
        printf("No HEAD, clean all\n");
        #endif
        CirQueue_Clean(a_pstCirQueue);
        return C_FALSE;
    }
    else if (0 != s16HeadPos) //if head is not the first, move it to the first
    {
        #if 0
        printf("xx xx HEAD ... ==> HEAD ...\n");
        #endif
        CirQueue_DeBlock(a_pstCirQueue, NULL, s16HeadPos);
        s16HeadPos = 0;
    }

    C_S16 s16TailPos = CirQueue_FindStr(a_pstCirQueue, strTail);
    if (s16TailPos >= 2) // data[0:2] is HEAD
    {
        if ((s16TailPos + 2) <= *a_pu8BuffSize)
        {
            #if 0
            //printf("new PACK\n");
            #endif
            CirQueue_DeBlock(a_pstCirQueue, a_pu8Buff, s16TailPos + 2);
            *a_pu8BuffSize = s16TailPos + 2;
            return C_TRUE;
        }
        else
        {
            #if 0
            printf("PACK is too long, give up\n");
            #endif
            CirQueue_DeBlock(a_pstCirQueue, NULL, s16TailPos + 2);
        }
    }
    else if (CirQueue_isFull(a_pstCirQueue)) //no tail and  the queue is full, clean the data
    {
        #if 0
        printf("No Tail && buff is full, clean all\n");
        #endif
        CirQueue_Clean(a_pstCirQueue);
    }

    return C_FALSE;
}



